const express = require('express');
const http = require('http');
const WebSocket = require('ws');

const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({server});

wss.on('connection', (ws) => {
    console.log('连接成功！');

    ws.on('message', (message) => {
        console.log('接收到消息：', message);

        // 将Buffer类型转化成String
        const msg = message.toString('utf-8');

        switch (msg) {
            case 'time':
                ws.send(`服务器时间: ${new Date().toLocaleTimeString()}`)
                break;
            case 'name':
                ws.send('服务器名称: 服务器9527！')
                break;
            default:
                ws.send(`服务返回数据: ${message}`);
                break;
        }
    });

    ws.on('close', () => {
        console.log('关闭连接');
    });
});

server.listen(3001, () => {
    console.log('Server is listening on port 3001');
});